# 1. 程序启动后，给⽤户提供查询接⼝，允许⽤户重复查股票⾏情信息(⽤到循环)
# 2. 允许⽤户通过模糊查询股票名，⽐如输⼊“啤酒”, 就把所有股票名称中包含“啤酒”的信息打印出来
# 3. 允许按股票价格、涨跌幅、换⼿率这⼏列来筛选信息，⽐如输⼊“价格>50”则把价格⼤于50的股票都打印，
# 输⼊“市盈率<50“，则把市盈率⼩于50的股票都打印，不⽤判断等于。
# 思路提示：加载⽂件内容到内存，转成dict or list结构，然后对dict or list 进⾏查询等操作。
# 这样以后就不⽤每查⼀次就要打开⼀次⽂件了，效率会⾼。
# 读取文件并解析内容到 list 的函数
import re


def read_stock_data(filename):
    stock_list = []
    with open(filename, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        for line in lines[1:]:  # 跳过文件的第一行
            parts = line.strip().split(',')
            try:
                current_price = float(parts[2])
                zhang_die_fu = float(parts[4].strip('%'))
                huan_shou_lv = float(parts[8].strip('%'))
                shi_ying_lv = float(parts[9]) if parts[9] not in ['-', '亏损'] else None

                stock = {
                    '股票代码': parts[0],
                    '股票名称': parts[1],
                    '当前价': current_price,
                    '涨跌额': parts[3],
                    '涨跌幅': zhang_die_fu,
                    '年初至今': parts[5],
                    '成交量': parts[6],
                    '成交额': parts[7],
                    '换手率': huan_shou_lv,
                    '市盈率(TTM)': shi_ying_lv,
                    '股息率': parts[10],
                    '市值': parts[11]
                }
                stock_list.append(stock)
            except ValueError as e:
                print(f"跳过解析出错的行: {line.strip()} - 错误详情: {e}")

    return stock_list


def print_stocks(stocks):
    if not stocks:
        print("未找到符合条件的股票。")
    for stock in stocks:
        print(stock)


def query_stock_by_name(stocks, name_fragment):
    result = [stock for stock in stocks if name_fragment in stock['股票名称']]
    return result


def query_stock_by_condition(stocks, condition):
    # 使用正则表达式在符号前后添加空格
    condition = re.sub(r'([<>])', r' \1 ', condition)
    key, operator, value = condition.split()
    value = float(value)

    if key == '价格':
        key = '当前价'
    elif key == '市盈率':
        key = '市盈率(TTM)'
    elif key == '换手率':
        key = '换手率'

    result = []
    for stock in stocks:
        if stock[key] is None:
            continue
        if operator == '>':
            if stock[key] > value:
                result.append(stock)
        elif operator == '<':
            if stock[key] < value:
                result.append(stock)
    return result


def main():
    stock_list = read_stock_data('..\\tempFile\\stock_data.txt')

    while True:
        print("\n请选择操作：")
        print("1. 查看所有股票信息")
        print("2. 模糊查询股票名称")
        print("3. 按条件查询股票信息")
        print("4. 退出")

        choice = input("输入选择（1/2/3/4）：")

        if choice == '1':
            print_stocks(stock_list)
        elif choice == '2':
            name_fragment = input("输入股票名称片段进行查询：")
            result = query_stock_by_name(stock_list, name_fragment)
            print_stocks(result)
        elif choice == '3':
            condition = input("输入条件（例如：价格>50、市盈率<50、换手率>50）：")
            result = query_stock_by_condition(stock_list, condition)
            print_stocks(result)
        elif choice == '4':
            break
        else:
            print("无效输入，请重新选择！")


if __name__ == "__main__":
    main()
